<template>
  <div>
    <div class="box">
      <div class="container" ref="container"
        @mousedown="touchStart"
        @mousemove="touchMove"
        @mouseup="touchEnd"
      >
        <div class="longer" ref="longer"></div>
        <div class="dot" ref="dot"></div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['currentTime', 'duration'],
  data() {
    return {
      touch: false,
      distance: 0,
      boxLeft: 0,
      containerWidth: 0,
    };
  },
  methods: {
    touchStart(e) {
      this.touch = true;
    },
    touchMove(e) {
      if (!this.touch) return;
      this.distance = e.pageX - this.boxLeft;
      this.move(this.distance);
    },
    touchEnd() {
      this.touch = false;
      const changeTime = (this.distance / this.containerWidth) * this.duration;
      this.$emit('changeTime', changeTime);
    },
    move(distance) {
      if (distance <= 0 || distance >= this.containerWidth) return;
        const percent = (distance / this.containerWidth) * 100;
        this.$refs.longer.style.width = `${ percent }%`;
        this.$refs.dot.style.transform = `translate(${ (distance / this.containerWidth) * 100 }vw)`;
    },
  },
  mounted() {
    this.containerWidth = this.$refs.container.getBoundingClientRect().width;
    this.boxLeft = this.$refs.container.getBoundingClientRect().left;
  },
  watch: {
    currentTime: {
      immediate: true,
      handler(val) {
        const distance = (val / this.duration) * this.containerWidth;
        if (this.touch) return;
        this.move(distance);
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  .container {
    // width: calc(100% - 208px);
    width: 100vw;
    background-color: rgb(91, 93, 94);
    height: 2px;
    position: relative;
    .longer {
      position: absolute;
      left: 0;
      background-color: pink;
      height: 3px;
    }
    .dot {
      width: 8px;
      height: 8px;
      background-color: pink;
      border-radius: 50%;
      position: absolute;
      top: -2px;
      left: -2px;
    }
  }
}
</style>
